var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
var ZYSmartSealWX = require("../../../../utils/ZY_Minprogram_SDK_V1.0");
var zysealsdk;
var commonUtil = require('../../../../utils/util');
const app = getApp();
Page({
  data:{
    // 用户id
    userId:0,
    // 盖章人员
    stampUser:{},
    // 启动序号
    startNo:0,
    // 启动id
    startId:0,
    // 启动印章人脸图片
    facePhoto:null,
    // 盖章序号
    stampNo:0,
    // 延时拍照速度
    photoSpeed:1,
    // 拍照倒计时
    countdown:1,
    showCountdown:false,
    // 延时拍照定时器
    photoTimer:null,
    // 盖章总次数
    stampTotalCount:0,
    // 印章信息
    sealData:{
      deviceId:null,// 设备id
      sealId:0,
      sealName:"请启动印章",// 印章名称
      mac:null,// 印章MAC地址
      battery:0,// 电量
      connectStatus:false,// 连接状态,
      companyId:0,// 所属公司id
    },
    // 单据信息
    applyData:{
      id:0,
      reason:"暂无可用的用印单据",
      availableCount:0,
      sealId:0,
      expireTime:"无"
    },
    // 位置信息
    positionData:{
      latitude:0,
      longitude:0,
      address:"暂无位置信息！"
    },
    // 连接成功盖章超时
    stampTimeOut:180,
    // 盖章超时定时器
    stampOverTimer:null,
    // 相机高度
    cameraHeight:500,
    // 底部高度
    footerHeight:80,
    // 上传的图片地址
    imageUrls:[],
    currentImageUrl:null,
    navbarData:{
      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '盖章自动拍照(0)', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     navbarHeight: app.globalData.height * 2 + 20
  },
  onLoad(){
    var _this = this;
    requestClient = new ZYRequestClient();
    // 获取盖章参数
    var sealData = wx.getStorageSync('sealData');
    var applyData = wx.getStorageSync('applyData');
    var positionData = wx.getStorageSync('positionData');
    // 盖章人员
    var stampUser = wx.getStorageSync('userInfo');
    _this.setData({
      sealData:sealData,
      applyData:applyData,
      positionData:positionData,
      userId:stampUser.id,
      stampUser:stampUser
    });
    var facePhoto = wx.getStorageSync('facePhoto');
    if(facePhoto != ''){
      _this.setData({
        facePhoto:facePhoto
      });
      wx.removeStorageSync('facePhoto');
    }
    // 读取延时拍照缓存
    var stampPhotoSpeed = wx.getStorageSync('stampPhotoSpeed');
    if(stampPhotoSpeed != ''){
      _this.setData({
        photoSpeed:parseInt(stampPhotoSpeed),
        countdown:parseInt(stampPhotoSpeed),
      });
    }
    // 设置相机高度，铺满整个屏幕
    wx.getSystemInfo({
      success: (result) => {
        _this.setData({
          cameraHeight:result.windowHeight - _this.data.navbarHeight - _this.data.footerHeight
        });
      },
    })
    // 设置拍照图片存储
    var stampImageInfo = {
      applyId:_this.data.applyData.id,
      imageUrls:[]
    };
    wx.setStorageSync('stampImageInfo', stampImageInfo);
    // 上传离线数据
    _this.uploadStampStroage();
    // 检查摄像机权限
    wx.getSetting({
      success(res){
        var authSetting = res.authSetting;
        if(authSetting['scope.camera']){
          // 连接印章
          setTimeout(() => {
            _this.connectDevice();
          }, 1000);
        } else {
          wx.showModal({
            title:'获取权限',
            content:'请授权摄像机权限，否则无法进行盖章拍照！授权后重新启动印章！',
            showCancel:false,
            success(r){
              
            }
          })
        }
      }
    })
  },
  // 盖章动作回调
  onStampCallBack(dataResult){
    var _this = this;
    // 计算剩余次数，重置超时时间
    _this.setData({
      'applyData.availableCount':_this.data.applyData.availableCount-1,
      stampTotalCount:_this.data.stampTotalCount + 1,
      stampTimeOut:180,
      stampNo:dataResult.data.stampNo,
      countdown:_this.data.photoSpeed,
      showCountdown:true,
    });
    // 设置标题，显示盖章总次数
    _this.setData({
      'navbarData.title':'盖章自动拍照('+_this.data.stampTotalCount + ')',
    });
    // 上传盖章动作
    var stampData = {
      applyId:_this.data.applyData.id,
      startId:_this.data.startId,
      sealId:_this.data.sealData.sealId,
      startNo:dataResult.data.startNo,
      stampNo:dataResult.data.stampNo,
      stampTime:dataResult.data.stampTime,
    };
    requestClient.pressStamp(stampData,function(res){
        if(!res.data.success){
          // 断开连接
          _this.disconnectDevice();
          // 离线存储
          var stampStorage = wx.getStorageSync('stampStorage');
          if(stampStorage == ''){
            stampStorage = [];
            stampStorage.push(stampData);
            wx.setStorageSync('stampStorage', stampStorage);
          } else {
            stampStorage.push(stampData);
            wx.setStorageSync('stampStorage', stampStorage);
          }
          wx.showToast({
            title: '网络异常，连接已断开!',
            icon:'none'
          })
        }
    },function(){
        // 断开连接
        _this.disconnectDevice();
        // 离线存储
        var stampStorage = wx.getStorageSync('stampStorage');
        if(stampStorage == ''){
          stampStorage = [];
          stampStorage.push(stampData);
          wx.setStorageSync('stampStorage', stampStorage);
        } else {
          stampStorage.push(stampData);
          wx.setStorageSync('stampStorage', stampStorage);
        }
        wx.showToast({
          title: '网络异常，连接已断开!',
          icon:'none'
        })
    });
    // 判断剩余次数是否为0，如果剩余次数为0，则关闭连接
    if(_this.data.applyData.availableCount == 0){
      // wx.showToast({
      //   title: '盖章已完成',
      //   icon:'none'
      // })
      _this.disconnectDevice();
    }
    // 判断是否在执行拍照
    if(_this.data.photoTimer != null){
      _this.setData({
        photoTimer:null,
        countdown:_this.data.photoSpeed
      });
      // 盖了章就得拍照
      _this.takePhoto();
      // 如果没有盖完，强制断开
      if(_this.data.applyData.availableCount > 0){
        _this.disconnectDevice();
        // 提示用户
        wx.showModal({
          title:'设备已断开',
          content:'盖章速度过快，设备已经断开，是否重新启动印章',
          confirmText:'重新启动',
          success(r){
            if(r.confirm){
              setTimeout(() => {
                _this.connectDevice();
              }, 1000);
            }
          }
        })
      }
    } else {
      // wx.showLoading({
      //   title: '正在启动拍照',
      //   mask:true,
      // })
      // 延时启动拍照
      var photoTimer = setInterval(() => {
        if(_this.data.countdown == 0){
          clearInterval(photoTimer);
          _this.setData({
            photoTimer:null,
            countdown:_this.data.photoSpeed
          });
          _this.takePhoto();
        } else {
          let countdown = _this.data.countdown -1;
          _this.setData({
            countdown:countdown
          });
        }
      },1000);
      // 赋值定时器
      _this.setData({
        photoTimer:photoTimer
      });
    }
  },
  // 报警事件回调
  onAlarmCallBack(dataResult){
    var _this = this;
    // 停止定时器
    if(_this.data.stampOverTimer){
      clearInterval(_this.data.stampOverTimer);
    }
    //判断报警类型
    var alarmRecordData = {};
    if(dataResult.data.alarm == 0x80){
      // 长按报警
      alarmRecordData = {
        sealId:_this.data.sealData.sealId,
        companyId:_this.data.sealData.companyId,
        type:1,
        address:_this.data.positionData.address,
        createUser:_this.data.userId,
        alarmTime:dataResult.data.alarmTime
      };
      wx.showModal({
        title:'违规盖章',
        content:'您已违规盖章！按压时间不能超过5秒！是否重新启动印章',
        confirmText:'重新启动',
        success(r){
          if(r.confirm){
            setTimeout(() => {
              _this.connectDevice();
            }, 1000);
          } else {
            _this.disconnectDevice();
          }
        }
      })
    } else {
      // 防拆报警
      alarmRecordData = {
        sealId:_this.data.sealData.sealId,
        companyId:_this.data.sealData.companyId,
        type:2,
        alarmTime:dataResult.data.alarmTime
      };
      _this.disconnectDevice();
      wx.showModal({
        title:'防拆报警',
        content:'您的印章已被拆，请联系管理员解除报警！',
        showCancel:false,
        success(r){
          
        }
      })
    }
    // 振动提醒
    wx.vibrateLong({
      success: (res) => {},
    })
    // 上传报警数据
    requestClient.uploadAlarmRecord(alarmRecordData,function(res){},function(){});
  },
  onShow(){
    var _this = this;
    zysealsdk = ZYSmartSealWX.getInstance({
      key:'2BFBF7DA7B2F11EB998B18C04D73E7B2'
    });
    // 订阅盖章动作上传事件
    zysealsdk.subscribeStampEvent(_this.onStampCallBack);
    // 订阅报警上传事件
    zysealsdk.subscribeAlarmEvent(_this.onAlarmCallBack);
  },
  // 连接设备
  connectDevice(){
    var _this = this;
    if(_this.data.applyData.availableCount == 0){
      return;
    }
    // 开始连接启动印章
    wx.showLoading({
      title: '正在启动印章',
      mask:true,
    })
    var deviceId = _this.data.sealData.deviceId;
    zysealsdk.connectDevice(deviceId,function(res){
      if(res.data.connectStatus){
        _this.setData({
          stampTimeOut:180,
          'sealData.connectStatus':true,
        });
        // 延时2秒
        setTimeout(() => {
          // 验证密钥
          zysealsdk.check(_this.onCheckCallBack);
        }, 2000);
        // 启动盖章超时定时器
        var t = setInterval(() => {
          _this.stampOverCallBack();
        }, 1000);
        _this.setData({
          stampOverTimer:t
        });
        _this.stampOverCallBack();
      } else {
        wx.hideLoading({
          success: (res) => {},
        })
        if(_this.data.sealData.connectStatus){
            // 停止定时器
            if(_this.data.stampOverTimer){
              clearInterval(_this.data.stampOverTimer);
            }
            wx.showModal({
            title:'设备断开连接',
            content:'您的印章已经异常断开，是否需要重新启动印章',
            confirmText:'重新启动',
            success(r){
              if(r.confirm){
                setTimeout(() => {
                  _this.connectDevice();
                }, 1000);
              }
            }
          })
          _this.setData({
            'sealData.connectStatus':false,
            showCountdown:false,
          });
        }
      }
    });
    // 判断连接超时
    setTimeout(() => {
      if(!_this.data.sealData.connectStatus){
        wx.showToast({
          title: '连接超时',
          icon:'error'
        })
        _this.disconnectDevice();
      }
    }, 3000);
  },
  // 盖章超时定时器回调
  stampOverCallBack(){
    var _this = this;
    // 计算盖章超时
    var stampTimeOut = _this.data.stampTimeOut;
    _this.setData({
      stampTimeOut:stampTimeOut - 1
    });
    if(_this.data.stampTimeOut == 0){
      _this.disconnectDevice();
    }
    // 计算是否到了失效时间
    var strExpireTime = _this.data.applyData.expireTime;
    var expireTime = commonUtil.stringToDate(strExpireTime);
    var now = new Date();
    if(expireTime - now <= 0){
      _this.disconnectDevice();
    }
  },
  // 验证密钥回调事件
  onCheckCallBack(dataResult){
    var _this = this;
    _this.setData({
      'sealData.battery':dataResult.data.battery,
    });
    // 验证失败，断开连接
    if(!dataResult.result){
      _this.disconnectDevice();
      wx.showToast({
        title: dataResult.message,
        icon:'none'
      })
      return;
    }
    // 判断电量，电量过低断开连接
    if(dataResult.data.battery <=10){
      _this.disconnectDevice();
      wx.showToast({
        title:'电量：' + dataResult.data.battery + '，已低于10%,请充电后再使用!',
        icon:'none',
        duration:2000
      })
      return;
    }
    // 判断报警标志
    if(dataResult.data.alarm !=0){
      //判断报警类型
      if(dataResult.data.alarm == 0x80){
        // 长按报警
        message = "您已违规盖章！按压时间不能超过5秒！";
        wx.showModal({
          title:'报警提示',
          content:message,
          success(r){

          }
        })
      } else {
        // 防拆报警
        // 提示用户是否解除报警
        wx.showModal({
          title:'报警提示',
          content:'当前印章已被拆！请管理员解除报警！',
          success(r){
            if(r.confirm){
                // 判断是否为当前印章的管理员
                var isAdmin = requestClient.checkAdminSealPermission(_this.data.sealData.sealId);
                if(isAdmin){
                  //发送解除报警
                  zysealsdk.removeAlarm(function(res){
                    // 解除报警后，断开连接
                    _this.disconnectDevice();
                    wx.showToast({
                      title: '报警已解除，请重新启动印章！',
                      mask:true,
                      icon:'none',
                      duration:3000
                    })
                  })
                } else {
                  _this.disconnectDevice();
                  wx.showToast({
                    title: '请联系此印章的管理员解除报警！',
                    icon:'none'
                  })
                }
            } else {
              _this.disconnectDevice();
            }
          }
        })
      }
      return;
    }
    // 设置盖章超时事件为3分钟
    zysealsdk.overTime(1,6,function(res){
      if(res.result){
        // 同步时间
        zysealsdk.localTime(1,new Date(),function(res){
          if(res.result){
            // 启动印章
            var strExpireTime = _this.data.applyData.expireTime;
            var expireTime = commonUtil.stringToDate(strExpireTime);
            var count = _this.data.applyData.availableCount;
            zysealsdk.startSeal(count,expireTime,_this.onStartCallBack)
          }
        })
      }
    })
  },
  // 启动印章回调
  onStartCallBack(dataResult){
    var _this = this;
    // 启动失败，断开连接
    if(!dataResult.result){
      _this.disconnectDevice();
      wx.showToast({
        title: '印章启动失败!',
        icon:'none'
      })
    } else {
      wx.hideLoading({
        success: (res) => {},
      })
      // 调用接口->启动印章
      _this.setData({
        startNo:dataResult.data.startNo,
        stampNo:0,
      });
      var startData = {
        applyId:_this.data.applyData.id,
        facePhotoUrl:_this.data.facePhoto,
        reason:_this.data.applyData.reason,
        sealId:_this.data.sealData.sealId,
        stampUser:_this.data.userId,
        startNo:_this.data.startNo,
        stampCount:0,
        companyId:_this.data.sealData.companyId,
        latitude:_this.data.positionData.latitude,
        longitude:_this.data.positionData.longitude,
        address:_this.data.positionData.address
      };
      requestClient.startStamp(startData,function(res){
        if(res.data.success){
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showToast({
            title: '启动成功!',
            icon:'sucess'
          })
          // 赋值启动序号
          _this.setData({
            startId:res.data.data
          });
        } else {
          _this.disconnectDevice();
          wx.showToast({
            title: '网络异常，启动失败!',
            icon:'none'
          })
        }
      },function(){
        _this.disconnectDevice();
        wx.showToast({
          title: '网络异常，启动失败!',
          icon:'none'
        })
      });
    }
  },
  // 断开连接
  disconnectDevice(callback){
    var _this = this;
    wx.hideLoading({
      success: (res) => {},
    })
    var _this = this;
    _this.setData({
      'sealData.connectStatus':false,
    });
    // 停止定时器
    if(_this.data.stampOverTimer){
      clearInterval(_this.data.stampOverTimer);
    }
    // 断开连接
    zysealsdk.disConnectDevice();
    if(callback){
      callback();
    }
  },
  // 上传离线数据
  uploadStampStroage(){
    // 上传离线数据
    var stampStorage = wx.getStorageSync('stampStorage');
    if(stampStorage){
      requestClient.storageStamp(stampStorage,function(res){
        // 上传成功，清空本地缓存
        if(res.data.success){
          wx.removeStorageSync('stampStorage');
        }
      },function(){

      });
    }
  },
  // 执行拍照
  takePhoto() {
    var _this = this;
    _this.setData({
      showCountdown:false,
    });
    // wx.hideLoading({
    //   success: (res) => {},
    // })
    const cameraContext = wx.createCameraContext();
    cameraContext.takePhoto({
      quality: 'normal',
      success: (res) => {
        // 上传照片
        requestClient.uploadImage(_this.data.userId,res.tempImagePath,function(res){
          _this.setData({
            currentImageUrl:res.data,
          });
          // 存储拍照图片信息
          var stampImageInfo = wx.getStorageSync('stampImageInfo');
          var imageUrls = stampImageInfo.imageUrls;
          imageUrls.push(res.data);
          stampImageInfo.imageUrls = imageUrls;
          wx.setStorageSync('stampImageInfo', stampImageInfo);
          _this.setData({
            // 图片数组反转
            imageUrls:stampImageInfo.imageUrls.reverse(),
          });
          // 如果完成盖章，提示用户关闭单据
          if(_this.data.applyData.availableCount == 0){
            _this.completePhoto();
          }
        });
      }
    })
  },
  error(e) {
    wx.showToast({
      title: '摄像机拍照错误!',
      icon:'error'
    })
    var _this = this;
    _this.onHide();
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000);
  },
  // 显示设置拍照速度
  bindShowPhotoSpeed(e){
    var _this = this;
    wx.showActionSheet({
      itemList: ['延时1秒拍照', '2秒', '3秒'],
      success (res) {
        var speed = res.tapIndex + 1;
        _this.setData({
          photoSpeed:speed,
          countdown:speed
        });
        // 存储拍照延时
        wx.setStorageSync('stampPhotoSpeed', speed)
      }
    })
  },
  // 查看拍照图片
  bindGoScanPhoto(e){
    var _this = this;
    wx.previewImage({
      showmenu:false,
      current:_this.data.currentImageUrl,
      urls:_this.data.imageUrls
    });
  },
  // 完成盖章拍照
  completePhoto(e){
    var _this = this;
    wx.showModal({
      title:'结束用印',
      content:'您确认结束用印吗',
      success(r){
        if(r.confirm){
            // 更新单据缓存
            wx.setStorageSync('applyData', _this.data.applyData)
            // 上传盖章图片
            var stampImageInfo = wx.getStorageSync('stampImageInfo');
            // 上传存储拍照的图片信息
            requestClient.uploadStampImages(stampImageInfo,function(res){
              if(res.data.data){
                  // 清空拍照缓存
                  wx.removeStorage({
                    key: 'stampImageInfo',
                  })
                  // 判断是否完成盖章
                  if(_this.data.applyData.availableCount > 0){
                    // 提醒用户未完成盖章
                    wx.showModal({
                      title:'盖章未完成',
                      content:'您的盖章次数剩余' + _this.data.applyData.availableCount + '次,是否关闭此单据',
                      confirmText:'直接关闭',
                      cancelText:'下次使用',
                      success(r){
                        if(r.confirm){
                          // 关闭单据
                          _this.closeApply();
                        } else {
                          if(_this.data.sealData.connectStatus){
                            _this.disconnectDevice(function(){
                              wx.switchTab({
                                url: '../index',
                              })
                            })
                          } else {
                            wx.switchTab({
                              url: '../index',
                            })
                          }
                        }
                      }
                    })
                } else {
                  // 关闭单据
                  _this.closeApply();
                }
              }
            });
        }
      }
    })
  },
  // 关闭单据
  closeApply(){
    var _this = this;
    if(_this.data.sealData.connectStatus){
      _this.disconnectDevice();
    }
    // 关闭单据
    requestClient.closeApply(_this.data.applyData.id,function(res){
      wx.showLoading({
        title: '正在关闭单据...',
        mask:true,
      })
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {},
        })
        wx.showModal({
          title:'盖章拍照',
          content:'您已完成盖章，可以在工作台->盖章记录中查看记录和盖章文件！',
          showCancel:false,
          success(r){
            if(r.confirm){
              // 跳转到主页
              wx.switchTab({
                url: '../index',
              })
            }
          }
        })
      }, 3000);
    })
  }
})